<?php
namespace App\Http\Controllers\Member;

use Illuminate\Http\Request;
use App\Models\Examination;
use App\Models\ExaminationHistory;
use App\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\CompanyInbox;
use App\Models\Company;
use App\Models\CompanyJobs;
use Illuminate\Support\Facades\Input;
/**
 *
 * @author Joker
 *        
 */
class ExaminationController extends MemberController
{
    public function index()
    {
        $sort = Input::get('sort',0);
        $query = ExaminationHistory::where('user_id','=',$this->uid);
        switch ($sort){
            case 1:  //分数
                $query->orderBy('score','desc');
                break;
            default:
                $query->orderBy('created_at','desc');
        }
        $ehistory = $query->orderBy('updated_at','desc')->paginate(20);
        return view('member.exam.index')->with('result',$ehistory)->with('sort',$sort);
    }
    
    /**
     * 用户考试
     * @param Request $req
     */
    public function store(Request $req)
    {
        $data = $req->all();//('company_id','job_id','examination_id','')
        $score = 0;
        $score_list = array();
        $answer_question = array();
        if(empty($this->uid))
            return $this->formatJson('error','请先登录！');
        if(empty($data['examination_id']) || !is_numeric($data['examination_id']) || $data['examination_id'] == 0 || $data['examination_id'] == 'undefined' )
        {
            return $this->formatJson('error','请选择相应的试卷！');
        }
        if(!empty($data['job_id'])&&!empty($data['company_id']))
        {
          $company = Company::find($data['company_id']);
          if(empty($company))
          {
            $this->formatJson('error','公司信息有误！');
          }
          $job = CompanyJobs::where(array('company_id'=>$data['company_id'],'jobs_id'=>$data['job_id']))->first();
          if(empty($job))
          {
            $this->formatJson('error','职位信息有误！');
          }
          if($job->status !== 1)
          {
            $this->formatJson('error','职位已关闭或未通过审核！');
          }
          $inbox = CompanyInbox::where(['company_id'=>$company->id,'job_id'=>$job->jobs_id,'user_id'=>$this->uid])->first();
          if(!empty($inbox))
            return $this->formatJson('error','您已投递过该职位,请勿重复投递，谢谢！');
        }
        else
        {
            return $this->formatJson('error','参数错误！');
        }
        $exam = Examination::with('questions')->where(array('id'=>$data['examination_id'],'company_id'=>$data['company_id']))->first();
        if(empty($exam))
        {
            return $this->formatJson('error','当前考试不存在！');
        }

        $questions = $exam->questions;
        if(count($questions)<=0)
        {
            return $this->formatJson('error','出现异常！');
        }  
        foreach ($questions as $ques)
        {
            $answer = $req->input('question_'.$ques->id,0);
            if(trim($answer) === $ques->answer)
            {
                $score += $exam->score;
                $score_list[$ques->id] =  $exam->score;
            }
            $answer_question[$ques->id] = $answer;
        }
        $insertData = [
            'company_id'        =>      $data['company_id'],
            'job_id'            =>      $data['job_id'],
            'examination_id'    =>      $data['examination_id'],
            'app'               =>      'jobs',
            'user_id'           =>      $this->uid,
            'questions'         =>      serialize($questions->toArray()),
            'answer_question'   =>      serialize($answer_question),
            'score_list'        =>      serialize($score_list),
            'ehtime'            =>      $data['ehtime'],
            'score'             =>      $score,
        ];
        if($score >= $exam->score_limit)
        {
            $resume = User::with('educationals')->with('experiences')->with('projects')->with('works')->with('otherinfo')->find($this->uid);
            if(count($resume->educationals)<=0 || $resume->educationals == null || count($resume->experiences)<=0 || count($resume->projects)<=0 || count($resume->otherinfo)<=0 )
                return $this->formatJson('error','抱歉，您的简历不完整，请先完善简历！');
            $insertResume = array(
                'company_id'        =>      $data['company_id'],
                'job_id'            =>      $data['job_id'],
                'user_id'           =>      $this->uid,
                'username'          =>      $resume->real_name,
                'degree'            =>      $resume->degree,
                'gznx'              =>      $resume->gznx,
                'resume'            =>      serialize($resume),
                'exam_id'           =>      $data['examination_id'],
                'resume_status'     =>      $resume->otherinfo->resume_status_id,
                'status'            =>      0
            );
        }
        $where=['company_id'=>$data['company_id'],'job_id'=>$data['job_id'],'user_id'=>$this->uid,'examination_id'=>$data['examination_id'],'app'=>'jobs'];
        DB::beginTransaction();
        try{
            $ehistory = ExaminationHistory::where($where)->first();
            if(!empty($ehistory) || $ehistory)
            {
                $ehistory->company_id       = $data['company_id'];
                $ehistory->job_id           = $data['job_id'];
                $ehistory->examination_id   = $data['examination_id'];
                $ehistory->user_id          = $this->uid;
                $ehistory->questions        = serialize($questions->toArray());
                $ehistory->answer_question  = serialize($answer_question);
                $ehistory->score_list       = serialize($score_list);
                $ehistory->ehtime           = $data['ehtime'];
                $ehistory->score            = $score;
                $ehistory->app              = "jobs";
                $ehistory->save();
            }
            else
            {
                $ehistory = ExaminationHistory::firstOrCreate($insertData);
            }
            if(!empty($resume))
            {
                CompanyInbox::firstOrCreate($insertResume);
            }
            DB::commit();
        }catch (\PDOException $e){
            DB::rollback();
            Log::info(['考试及投递简历出错'=>$e->getMessage()]);
            return $this->formatJson('error','考试失败！');
        }
        if($score < $exam->score_limit)
            return $this->formatJson('error','抱歉，您的考试不及格，请选择重考，谢谢！',$ehistory);
        if(empty($resume))
            return $this->formatJson('error','请先完善个人简历！',$ehistory);
            
        return $this->formatJson('success','恭喜您，您已通过考试并申请［'.$exam->companyBelongs->name.'］公司的［'.$job->title.'］职位成功！',$ehistory);
        
    }
    
    /**
     * 没有考试的职位，投递简历
     * @param Request $req
     */
    public function resume(Request $req)
    {
        $data = $req->only('company_id','job_id');
        if(empty($this->uid))
            return $this->formatJson('error','请先登录！');
        $company = Company::find($data['company_id']);
        if(empty($company))
        {
            $this->formatJson('error','公司信息有误！');
        }
        $job = CompanyJobs::where(array('company_id'=>$data['company_id'],'jobs_id'=>$data['job_id']))->first();
        if(empty($job))
        {
            $this->formatJson('error','职位信息有误！');
        }
        if($job->status !== 1)
        {
            $this->formatJson('error','职位已关闭或未通过审核！');
        }
        $inbox = CompanyInbox::where(['company_id'=>$company->id,'job_id'=>$job->jobs_id,'user_id'=>$this->uid])->first();
        if(!empty($inbox))
            return $this->formatJson('error','您已投递过该职位,请勿重复投递，谢谢！');
        
        $resume = User::with('educationals')->with('experiences')->with('projects')->with('works')->with('otherinfo')->find($this->uid);
        if(count($resume->educationals)<=0 || $resume->educationals == null || count($resume->experiences)<=0 || count($resume->projects)<=0 || count($resume->otherinfo)<=0 )
            return $this->formatJson('error','抱歉，您的简历不完整，请先完善简历！');
        $insertResume = array(
            'company_id'        =>      $data['company_id'],
            'job_id'            =>      $data['job_id'],
            'user_id'           =>      $this->uid,
            'username'          =>      $resume->real_name,
            'degree'            =>      $resume->degree,
            'gznx'              =>      $resume->gznx,
            'resume'            =>      serialize($resume),
            'exam_id'           =>      0,
            'resume_status'     =>      $resume->otherinfo->resume_status_id,
            'status'            =>      0
        );
        $myinbox = CompanyInbox::firstOrCreate($insertResume);
        return $this->formatJson('success','恭喜您，申请［'.$company->name.'］公司的［'.$job->title.'］职位成功！',$myinbox);
    }

    /**
     * 就业指南考试
     */
    public function employ(Request $req)
    {
        $data = $req->all();
        $score = 0;
        $score_list = array();
        $answer_question = array();
        if(empty($this->uid))
            return $this->formatJson('error','请先登录！');
        if(empty($data['examination_id']) || !is_numeric($data['examination_id']) || $data['examination_id'] == 0 || $data['examination_id'] == 'undefined' )
        {
            return $this->formatJson('error','请选择相应的试卷！');
        }
        
        if(empty($data['app']) || $data['app'] !=='employ'){
            return $this->formatJson('error','参数错误！');
        }
        $exam = Examination::with('questions')->where(array('id'=>$data['examination_id'],'company_id'=>0))->first();
        if(empty($exam))
        {
            return $this->formatJson('error','当前考试不存在！');
        }
    
        $questions = $exam->questions;
        if(count($questions)<=0)
        {
            return $this->formatJson('error','出现异常！');
        }
        foreach ($questions as $ques)
        {
            $answer = $req->input('question_'.$ques->id,0);
            if(trim($answer) === $ques->answer)
            {
                $score += $exam->score;
                $score_list[$ques->id] =  $exam->score;
            }
            $answer_question[$ques->id] = $answer;
        }
        $insertData = [
            'company_id'        =>      0,
            'job_id'            =>      $data['job_id'],
            'examination_id'    =>      $data['examination_id'],
            'app'               =>      $data['app'],
            'user_id'           =>      $this->uid,
            'questions'         =>      serialize($questions->toArray()),
            'answer_question'   =>      serialize($answer_question),
            'score_list'        =>      serialize($score_list),
            'ehtime'            =>      $data['ehtime'],
            'score'             =>      $score,
        ];
        $where=['company_id'=>$data['company_id'],'job_id'=>$data['job_id'],'user_id'=>$this->uid,'examination_id'=>$data['examination_id'],'app'=>$data['app']];
        DB::beginTransaction();
        try{
            $ehistory = ExaminationHistory::where($where)->first();
            if(!empty($ehistory) || $ehistory)
            {
                $ehistory->company_id       = $data['company_id'];
                $ehistory->job_id           = $data['job_id'];
                $ehistory->examination_id   = $data['examination_id'];
                $ehistory->user_id          = $this->uid;
                $ehistory->questions        = serialize($questions->toArray());
                $ehistory->answer_question  = serialize($answer_question);
                $ehistory->score_list       = serialize($score_list);
                $ehistory->ehtime           = $data['ehtime'];
                $ehistory->score            = $score;
                $ehistory->save();
            }
            else
            {
                $ehistory = ExaminationHistory::firstOrCreate($insertData);
            }
            DB::commit();
        }catch (\PDOException $e){
            DB::rollback();
            Log::info(['考试及投递简历出错'=>$e->getMessage()]);
            return $this->formatJson('error','考试失败！');
        }
        if($score < $exam->score_limit)
            return $this->formatJson('error','抱歉，您的考试不及格，可选择重考！',$ehistory);
    
        return $this->formatJson('success','恭喜您，考试通过，谢谢您的参与！',$ehistory);
    }

    /**
     * 删除
     */
    public function destroy($id)
    {
        $exam = ExaminationHistory::where(array('id'=>$id,'user_id'=>$this->uid))->first();
        if(empty($exam))
        {
            return  $this->formatJson('falied','抱歉，资源不存在!');
        }
        else
        {
            $exam->delete();
            return $this->formatJson('success','删除考试成功！');
        }
    }
}